package org.springblade.metadata.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.springblade.metadata.service.FTPFileWriter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;

@Component
@Slf4j
public class FTPFileWriterImpl implements FTPFileWriter {

    protected FTPClient ftpClient;
    @Value("${ftp.host}")
    private String host;
    @Value("${ftp.port}")
    private Integer port;
    @Value("${ftp.username}")
    private String userName;
    @Value("${ftp.pwd}")
    private String pwd;

	@Value("${ftp.directory}")
	private String directoryStr;


    /*@PostConstruct
    public void init() {
        if (this.FTPProperties.isAutoStart()) {
            log.debug("Autostarting connection to FTP server.");
            this.open();
        }
    }*/
	private boolean open() {
		close();
		log.info("Connecting and logging in to FTP server.");
		ftpClient = new FTPClient();
		boolean loggedIn = false;
		try {
			ftpClient.connect(host, port);
			loggedIn = ftpClient.login(userName, pwd);
			log.info("host=" + host + " port=" + port + " loggedIn=" + loggedIn);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return loggedIn;
	}
	private void close() {
		if (ftpClient != null) {
			try {
				ftpClient.logout();
				ftpClient.disconnect();
			} catch (Exception e) {
				//log.error(e.getMessage(), e);
			}
		}
	}
    @Override
	public String saveFile(InputStream inputStream, String fileName, boolean append) {
		try {
			this.open();
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			if (!ftpClient.changeWorkingDirectory(directoryStr)){
				ftpClient.makeDirectory(directoryStr);
				ftpClient.changeWorkingDirectory(directoryStr);
			}
			ftpClient.enterLocalPassiveMode();
//			String result = directoryStr + File.separator + fileName;
			String result = directoryStr + "/" + fileName;
			boolean f;
            log.debug("Trying to store a file to destination path " + result);
            if(append){
                f = ftpClient.appendFile(fileName, inputStream);
			} else {
                f = ftpClient.storeFile(new String(fileName.getBytes(),"iso-8859-1"), inputStream);
			}
			inputStream.close();
			this.close();

			return f ? result : null;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }
	@Override
    public String saveFile(String sourcePath, String destPath, boolean append) {
        InputStream inputStream = null;
        try {
            inputStream = new ClassPathResource(sourcePath).getInputStream();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return null;
        }
        return this.saveFile(inputStream, destPath, append);
    }

}
